package com.idea.relax.tool.core.tree;


import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

/**
 * @author azhao
 */
public class TreeBuild<T> extends ListTree<T> {
    public List<T> buildList(List<T> list, Function<T, List<T>> fun) {
        if (list == null) {
            return new ArrayList<>();
        }
        List<T> listResult = new ArrayList<>();
        list.forEach(e -> listResult.addAll(buildList(e, fun)));
        return listResult;
    }

    public List<T> buildList(T t, Function<T, List<T>> fun) {
        if (t == null) {
            return new ArrayList<>();
        }
        List<T> listResult = new ArrayList<>();
        buildList(t, listResult, fun);
        listResult.add(t);
        return listResult;
    }

    private void buildList(T t, List<T> buildList, Function<T, List<T>> fun) {
        List<T> listResult = fun.apply(t);
        buildList.addAll(listResult);
        for (T m : listResult) {
            buildList(m, buildList, fun);
        }
    }
}
